import time
import os
import random
import pandas as pd
import pythoncom
from PySide2.QtCore import QThread, Signal
from vjiajia_utils.wechat_utils import get_wechat_version
from wechat_operations.v3_operations import WeChatV3Operations
from wechat_operations.v4_operations import WeChatV4Operations
from vjiaja_constant.vjiaja_constant import TaskCompletionState
import debugpy

class HumanizedFriendAdditionWorker(QThread):
    progress_signal = Signal(int, int, int, int)  # 文件行数，已经处理的行数，成功发送的数量，处理下一行剩余的时间
    interval_remaining_signal = Signal(int)
    finished_signal = Signal(str)
    error_signal = Signal(str)
    log_signal = Signal(str)
    force_stop_signal = Signal()

    def _log(self, message):
        if self.log_signal:
            self.log_signal.emit(message)
        print(message)
    def __init__(self, file_path, apply_msg, prefix, interval, target_num, tag):
        super().__init__()
        self.file_path = file_path
        self.apply_msg = apply_msg
        self.prefix = prefix
        self.min_interval = int(interval * 0.7)
        self.max_interval = int(interval * 1.3)
        self.target_num = target_num
        self.tag = tag
        self._is_running = True
        self._is_paused = False
        #self.wechat_ops = WeChatV4Operations(self._log)
        self.wechat_ops = None

    def run(self):
        #debugpy.debug_this_thread()
        pythoncom.CoInitialize()
        try:
            status = self._process_excel_file()
            status_map = {
                TaskCompletionState.FINISHED: "completed",
                TaskCompletionState.INTERRUPTED: "user_stopped",
                TaskCompletionState.THROTTLED: "rate_limited", 
                TaskCompletionState.FAILED: "error"
            }
            self._log(f"Excel文件处理完成,状态 {status_map[status]}")
            self.finished_signal.emit(status_map[status])
        except Exception as e:
            self.error_signal.emit(str(e))
            self.finished_signal.emit("error")
        finally:
            pythoncom.CoUninitialize()

    def _process_excel_file(self):
        df = pd.read_excel(self.file_path, dtype={'移动电话': str, '姓名': str, '状态': str})
        if '状态' not in df.columns:
            df['状态'] = ""

        total = len(df)
        processed = 0
        send_count = 0

        current_time = time.strftime("%Y%m%d%H%M", time.localtime())
        new_file_path = f"{os.path.splitext(self.file_path)[0]}_{current_time}.xlsx"

        for index, row in df.iterrows():
            if not self._check_running():
                self.force_stop_signal.emit()
                return TaskCompletionState.INTERRUPTED
           
            phone = str(row['移动电话']).strip()
            name = str(row['姓名']).strip() if pd.notna(row['姓名']) else ""
            status = str(row['状态']).strip()

            if status in ["已发送好友申请", "已添加好友", "账号不存在"]:
                processed += 1
                continue

            version = get_wechat_version()
            print(f"微信版本号: {version}")
            # 微信V4无法看到UI结构，只适配V3
            #self.wechat_ops = WeChatV3Operations(self._log, phone, name, self.apply_msg, self.prefix, self.tag)
            if version == None:
                print(f"微信 V3")
                self.wechat_ops = WeChatV3Operations(self._log, phone, name, self.apply_msg, self.prefix, self.tag)
            else:
                print(f"微信 V4")
                self.wechat_ops = WeChatV4Operations(self._log, phone, name, self.apply_msg, self.prefix, self.tag)

            if not self.wechat_ops._activate_wechat():
                self._log("微信窗口未找到，请检查是否已打开微信！")
                continue

            if self.wechat_ops.is_add_friend_busy(self.wechat_ops.wechat_window):
                self._log("用户添加频繁，请休息24小时再试！")
                return TaskCompletionState.THROTTLED

            if not self.wechat_ops._random_click_sidebar():
                self._log("没找到可点击的侧边栏按钮！")
                continue

            if not self.wechat_ops.click_sidebar_entry():
                self._log("没找到侧边栏目标入口！")
                continue

            self._log("查找取消按钮...")
            self.wechat_ops._click_cancel_button()

            result = self._process_contact()
            if result:
                df.at[index, '状态'] = result
                if result == "已发送好友申请":
                    send_count += 1
                    if send_count >= self.target_num:
                        self._log("已到达目标添加数，停止添加！")
                        return TaskCompletionState.FINISHED

            self._log("开始下一个联系人")
            processed += 1
            df.to_excel(new_file_path, index=False)
            self._update_progress(total, processed, send_count)
            self._random_wait()

        return TaskCompletionState.FINISHED

    def _process_contact(self):
        try:
            return self.wechat_ops.add_friend()
        except Exception as e:
            self.log_signal.emit(f"处理出错: {str(e)}")
            return None

    def _check_running(self):
        while self._is_paused:
            time.sleep(1)
        return self._is_running

    def _update_progress(self, total, processed, send_count):
        progress = int((processed / total) * 100)
        self.progress_signal.emit(total, processed, send_count, 0)

    def _random_wait(self):
        wait_sec = random.randint(self.min_interval, self.max_interval)
        for remaining in range(wait_sec, -1, -1):
            self.interval_remaining_signal.emit(remaining)
            self._log(f"下一个添加: {remaining} s")
            if not self._check_running():
                break
            time.sleep(1)

    def stop(self):
        self._log("点击停止按钮")
        self._is_running = False

    def pause(self):
        self._is_paused = True

    def resume(self):
        self._is_paused = False